import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { ConfirmationService, Message } from 'primeng/primeng';
import { UserModel } from '../models/login/user-model';
import { InterceptorService } from '../share/interceptor.service';
import { AuthGuardService } from '../share/auth-guard.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})



export class LoginComponent implements OnInit {

  public user: UserModel = new UserModel();
  /**
     * TODO：
     * 两个用户同时登录弹框提示，确保一人在线。
     * 此功能尚未启用，正式生产环境启用
     */
  msgs: Message[] = [];
  confirm() {
    this.confirmationService.confirm({
      message: '用户已在线，如果您继续登陆，将强制其他用户下线',
      header: '温馨提示',
      icon: 'fa fa-question-circle',
      accept: () => {

        /**
         * 退出跳转到登录页
         *
         */
        const quitURL = 'authorizationManagement-web/access/logout/' + this.user.userCode;

        this.http.get(quitURL).subscribe(
          res => {
            if (res.json().code == '0000') {          
              this.doLogin(this.user.userCode, this.user.password);
            }
          }
        );
      },
      reject: () => {
        this.router.navigateByUrl('login');
      }
    });
  }


  logoRUL = 'assets/images/login/default-avatar.png';

  constructor(
    public router: Router,
    public http: InterceptorService,
    public authGuardService: AuthGuardService,
    public confirmationService: ConfirmationService

  ) { }

  ngOnInit() {
    document.body.style.backgroundImage = "assets/images/login/webp.webp";
  }

  /**
   * 十二期杨晓风-2017年11月13日18:08:33
   * ---------------------------------------------登录-------------------------------------
   * @param userCode 用户名
   * @param password 密码
   */
  message = "";
  display = false;
  public doLogin(userCode: string, password: string) {
    if (this.isStrEmpty(this.user.userCode) ){
      document.getElementById('user_name').focus();
      this.showDialog('账号不能为空，请填写账号');
      return;
    }
    if (this.isStrEmpty(this.user.password)) {
      this.showDialog('密码不能为空，请填写密码');
      document.getElementById("password").focus();
      return;
    }
    const userLoginURL = 'authorizationManagement-web/access/login';
    const body = JSON.stringify({
      userCode: userCode.trim(),
      password: password.trim()
    });

    this.http.post(userLoginURL, body).toPromise().then(
      res => {
        if (res.json().code === '0000') {
            this.user.userRealName = res.json().data.userName;
            localStorage.setItem('Authorization', res.json().data.token);
            localStorage.setItem('userId', res.json().data.id);
            localStorage.setItem('userCode', res.json().data.userCode);
            localStorage.setItem('userName', res.json().data.userName);
            this.router.navigateByUrl('workspace');
        } else if (res.json().code === '1001') {
          //如果code值是1001，已经登录，调用强制用户下线方法
          this.confirm();
        } else {
          this.message = "登录失败";
          // alert('亲，抱歉登录失败,请检查用户名和密码是否正确');
          this.showDialog('亲，抱歉登录失败,请检查用户名和密码是否正确');
          this.display = true;
        }
      }
    ).catch(this.handleError)
  }

  public handleError(error: any): Promise<any> {
    // alert('亲，抱歉登录失败奥');
    this.showDialog('亲，抱歉登录失败奥');
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

  doSign() {
    this.router.navigateByUrl('sign');
  }
  doReset(){
    this.router.navigateByUrl('reset-password');
  }
  DiaMessage: "";

  /**
     * 提示框
     */
  showDialog(string) {
    this.DiaMessage = string;
    this.display = true;
    let com = this;
    var t = setTimeout(function () { com.display = false }, 1500);
  }

  closeDialog() {
    this.display = false;
  }
  /**
  * 判断字符串是否为 null或为 "" 值，是则返回true，否返回false
  * @param obj 字符串
  */
 isStrEmpty(obj: string) {
  if (obj == undefined || obj == null || obj.trim() == "") {
    return true;
  }
  return false;
}
}